import Vue from 'vue'
import {
  ToastPlugin
} from 'vux'
Vue.use(ToastPlugin)
const websocket = new Vue({
  data() {
    return {
      ws: '',
      usertel:'',   // 当前的分机号
      userInfo: '',
      state: 0,
      data: {},
      keepalive: null,
      ipSessionId:null
    }
  },
  methods: {
    init(userInfo) {
      console.log('websocket init')
      if(!userInfo){
        return
      }
      this.userInfo = userInfo
      this.state = 1
      // const wsUrl = window.path.slice(window.path.indexOf(':'))
      const wsUrl = window.ipurl.slice(window.path.indexOf(':'))
      console.log('wsUrl:',wsUrl)
      this.ws = new WebSocket(`ws${wsUrl}websocketTwo`)
      // this.ws = new WebSocket(`ws://192.168.0.140:8080/css/websocketTwo`)
      this.ws.onopen = this.WSonOpen;
      this.ws.onmessage = this.WSonMessage;
      this.ws.onclose = this.WSonClose;
      this.ws.onerror = this.WSonError;
    },
    WSonOpen() {
      let sessionId = this.ipSessionId
      this.$vux.toast.show({
        text: '开始连接',
        type: 'text'
      })
      this.WsSend(`sessionId${sessionId}`)
      this.keepAliveHandle()
    },
    WsSend: function (s) {
      console.log('发出',s)
      this.ws.send(s)
    },
    WSonMessage(evt) {
      if (typeof (evt.data) == "string") {
        this.textHandler(evt.data);
      } else {
        var reader = new FileReader();
        reader.readAsText(evt.data);
        reader.onload = (e) => {
          if (e.target.readyState == FileReader.DONE) {
            this.textHandler(e.target.result); //协议返回
          }
        }
      }
    },
    WSonClose() {
      this.$vux.toast.show({
        text: '连接结束',
        type: 'text'
      })
      this.reset();
    },
    WSonError() {
      this.$vux.toast.show({
        text: '连接出错',
        type: 'text'
      })
      this.reset();
    },
    textHandler(data) {
      if(data !== ''){
        console.log('返回的data：', data)
        this.data = JSON.parse(data)
      }
    },
    keepAliveHandle() {
      this.keepalive = setInterval(() => {
        this.WsSend('keepalive')
      // }, 30 * 1000);
      }, 3 * 1000);
    },
    stopKeepAlive() {
      clearInterval(this.keepalive)
    },
    reset() {
      this.state = 0;
      this.stopKeepAlive();
    },
  }
})
window.websocket = websocket
export default websocket
